{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 括号匹配算法\n",
    "\n",
    "判断括号是否正确关闭了\n",
    "\n",
    "sentence=\"0{abc}{de}(f)[(g)]9\"  \n",
    "sentence=\"0{abc}{de}(f)[(g)9\"\n",
    "\n",
    "\n",
    "\n",
    "<img src=\"./backet-match-stack.png\" style=\"margin-left:0px;\"/>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def bracket_match(sentence):\n",
    "    # 括号的反向匹配，用于遇到了右括号，获取对应的最括号\n",
    "    brackets_map = {\n",
    "        ')': '(' , \n",
    "        ']': '[' , \n",
    "        '}': '{' ,\n",
    "        '>': '<' \n",
    "    }\n",
    "\n",
    "    # 使用栈存储左括号列表，每次遇到右括号就匹配栈顶\n",
    "    stack = [] \n",
    "    label = True\n",
    "    for iter_char in sentence:\n",
    "        # 遇到了左括号，则入stack\n",
    "        if iter_char in brackets_map.values():\n",
    "            stack.append(iter_char)\n",
    "        \n",
    "        # 遇到了右括号，则进行判断\n",
    "        if iter_char in brackets_map:\n",
    "            # 如果栈已经空了，则返回匹配失败\n",
    "            if len(stack) < 1:\n",
    "                return False\n",
    "            \n",
    "            if brackets_map[iter_char] == stack[-1]:\n",
    "                stack.pop() # 如果该括号匹配成功，则弹出栈顶\n",
    "            else:\n",
    "                return False # 否则，直接失败\n",
    "    \n",
    "    # 如果栈不为空，返回失败\n",
    "    if stack != []:\n",
    "        return False\n",
    "    return True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sentence=\"0{abc}{de}(f)[(g)]9\"\n",
    "bracket_match(sentence)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sentence=\"0{abc}{de}(f)[(g)9\"\n",
    "bracket_match(sentence)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
